package org.nowcoder.leetcode.BTree;

import java.util.*;

/**
 * Title  : 107. Binary Tree Level Order Traversal II
 * Source : https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/
 * Author : XrazYang
 * Date   : 2023-08-30
 */
public class LeetCode_107 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        //边界条件
        if (root == null) {
            return result;
        }
        Queue<TreeNode> que = new ArrayDeque<>();
        Deque<List<Integer>> sta = new ArrayDeque<>();
        que.offer(root);
        while (!que.isEmpty()) {
            int size = que.size();
            List<Integer> temp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = que.poll();
                temp.add(node.val);
                if (node.left != null) {
                    que.offer(node.left);
                }
                if (node.right != null) {
                    que.offer(node.right);
                }
            }
            sta.push(temp);
        }
        while (!sta.isEmpty()) {
            result.add(sta.pop());
        }
        return result;
    }
}
